package com.geekerp.authorization_server.sms2;

import com.geekerp.authorization_server.service.SmsUserService;
import com.geekerp.authorization_server.support.RedisOperator;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Map;

@Component
public class SmsAuthenticationProvider implements AuthenticationProvider {

    private final String REDIS_LOGIN_CAPTCHA_KEY = "captcha:";
    private final SmsUserService userDetailsService;

    private final RedisOperator redisUtils;

    public SmsAuthenticationProvider(SmsUserService userDetailsService, RedisOperator redisUtils) {
        this.userDetailsService = userDetailsService;
        this.redisUtils = redisUtils;
    }


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String phone = (String) authentication.getPrincipal();  // 获取手机号
        String captcha = (String) authentication.getCredentials();  // 获取验证码

        if(redisUtils.get(REDIS_LOGIN_CAPTCHA_KEY + phone)==null){
            throw new BadCredentialsException("验证码已过期");
        }
        // 验证码是否正确
        String redisCaptcha = redisUtils.get(REDIS_LOGIN_CAPTCHA_KEY + phone).toString();
        if (redisCaptcha == null || !redisCaptcha.equals(captcha)) {
            throw new BadCredentialsException("验证码错误");
        }

        // 验证用户信息
        UserDetails userDetails = userDetailsService.loadUserByPhoneNum(phone);
        if (userDetails == null) {
            throw new BadCredentialsException("未找到对应的用户,请先注册");
        }

        // 创建已认证的Token
        return new SmsAuthenticationToken(userDetails, null, userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SmsAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
